const http = require('http');
const querystring = require('querystring');

// HTTP请求工具函数
function makeRequest(options, postData = null) {
  return new Promise((resolve, reject) => {
    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      res.on('end', () => {
        try {
          const jsonData = JSON.parse(data);
          resolve({ status: res.statusCode, data: jsonData });
        } catch (e) {
          resolve({ status: res.statusCode, data: data });
        }
      });
    });

    req.on('error', (err) => {
      reject(err);
    });

    if (postData) {
      req.write(postData);
    }
    req.end();
  });
}

// 测试智能推荐数据结构
async function testRecommendationDataStructure() {
  try {
    console.log('🧪 测试智能推荐数据结构...\n');
    
    const testParams = {
      city: '北京',
      occasion: '上班',
      includeWeather: 'true',
      useAI: 'true'
    };
    
    const queryString = querystring.stringify(testParams);
    const options = {
      hostname: 'localhost',
      port: 7001,
      path: `/api/v1/recommendation/smart?${queryString}`,
      method: 'GET',
      headers: {
        'Authorization': 'Bearer test-token'
      }
    };
    
    const response = await makeRequest(options);
    
    if (response.status === 200) {
      console.log('✅ 请求成功!\n');
      
      const data = response.data.data;
      
      // 分析数据结构
      console.log('📊 数据结构分析:');
      console.log(`• 推荐数量: ${data.recommendations?.length || 0}`);
      console.log(`• 数据源: ${data.source || '未知'}`);
      console.log(`• 请求ID: ${data.requestId || '无'}`);
      console.log(`• 时间戳: ${data.timestamp || '无'}\n`);
      
      if (data.recommendations && data.recommendations.length > 0) {
        console.log('🎯 推荐详情分析:\n');
        
        data.recommendations.forEach((rec, index) => {
          console.log(`--- 搭配 ${index + 1} ---`);
          console.log(`策略: ${rec.strategy || '未知'}`);
          console.log(`评分: ${rec.score || 0}`);
          console.log(`标签: ${rec.tags?.join(', ') || '无'}`);
          console.log(`理由: ${rec.reason || '无'}`);
          console.log(`衣服ID列表: [${rec.clothingIds?.join(', ') || '无'}]`);
          console.log(`衣服数量: ${rec.items?.length || 0}`);
          
          if (rec.items && rec.items.length > 0) {
            console.log('衣服详情:');
            rec.items.forEach((item, itemIndex) => {
              console.log(`  ${itemIndex + 1}. ${item.displayName || item.name}`);
              console.log(`     ID: ${item.id}`);
              console.log(`     分类: ${item.categoryName || item.category?.name || '未知'}`);
              console.log(`     颜色: ${item.color || '未知'}`);
              console.log(`     品牌: ${item.brand || '无'}`);
              console.log(`     风格: ${item.style || '无'}`);
            });
          }
          console.log('');
        });
        
        // 验证数据结构完整性
        console.log('🔍 数据结构验证:');
        let isValid = true;
        
        data.recommendations.forEach((rec, index) => {
          // 检查必需字段
          if (!rec.clothingIds || !Array.isArray(rec.clothingIds)) {
            console.log(`❌ 搭配${index + 1}: clothingIds字段缺失或格式错误`);
            isValid = false;
          }
          
          if (!rec.items || !Array.isArray(rec.items)) {
            console.log(`❌ 搭配${index + 1}: items字段缺失或格式错误`);
            isValid = false;
          }
          
          if (rec.items && rec.clothingIds) {
            if (rec.items.length !== rec.clothingIds.length) {
              console.log(`❌ 搭配${index + 1}: items和clothingIds数量不匹配`);
              isValid = false;
            }
            
            // 检查每个item的数据结构
            rec.items.forEach((item, itemIndex) => {
              if (!item.id || !item.name) {
                console.log(`❌ 搭配${index + 1}衣服${itemIndex + 1}: 缺少id或name字段`);
                isValid = false;
              }
              
              if (!item.categoryName && !item.category?.name) {
                console.log(`⚠️ 搭配${index + 1}衣服${itemIndex + 1}: 缺少分类信息`);
              }
            });
          }
        });
        
        if (isValid) {
          console.log('✅ 数据结构验证通过！');
        } else {
          console.log('❌ 数据结构验证失败！');
        }
        
      } else {
        console.log('⚠️ 没有推荐数据');
      }
      
    } else {
      console.error(`❌ 请求失败，状态码: ${response.status}`);
      console.error('响应:', response.data);
    }
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
  }
}

// 运行测试
async function runTest() {
  console.log('🚀 开始数据结构测试\n');
  
  // 等待服务启动
  console.log('⏳ 等待服务启动...');
  await new Promise(resolve => setTimeout(resolve, 2000));
  
  await testRecommendationDataStructure();
  
  console.log('\n✨ 测试完成!');
}

runTest().catch(console.error);
